#include <my_header.h>

/* Usage: ./3_client_select_reset */
int main(void){                                  

    char *ip = "192.168.229.128";
    char *port = "8080";

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(socket_fd, -1, "socket");

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);
    // 建立连接
    int res_conn = connect(socket_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
    ERROR_CHECK(res_conn, -1, "connect");
    
    // 定义一个监听集合
    fd_set set;
    while(1)
    {
        // 设置监听集合
        FD_ZERO(&set);
        FD_SET(STDIN_FILENO, &set);
        FD_SET(socket_fd, &set);

        // 使用select监听集合是否可读
        int res_select = select(socket_fd +1, &set, NULL, NULL, NULL);
        ERROR_CHECK(res_select, -1, "select");

        // 有就绪
        if(FD_ISSET(STDIN_FILENO, &set))
        {
            // 读取标椎输入，给对方发信息
            char buf[60] = {0};
            read(STDIN_FILENO, buf, sizeof(buf) -1);
            ssize_t res_send = send(socket_fd, buf, sizeof(buf), 0);
            ERROR_CHECK(res_send, -1, "send");
        }
        if(FD_ISSET(socket_fd, &set))
        {
            char buf[60]  ={0};
            ssize_t res_recv = recv(socket_fd, buf, sizeof(buf), 0);
            if(res_recv == 0)
            {
                printf("server closed！ \n");
                break;
            }
            printf("server message:%s \n", buf);
        }
    }

    // 关闭socket文件描述符
    close(socket_fd);
    return 0;
}


